<template>
  <div class="block">
    <span
      class="demonstration"
      style="font-size:14px;color: #303133; line-height: 40px;margin-right:10px;"
    >城市地区</span>
    <el-cascader
      clearable
      filterable
      v-model="value"
      :options="options"
      :props="{ expandTrigger: 'hover' }"
      @change="handleChange"
      style="width:300px;"
    ></el-cascader>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: [],
      options: [
        {
          value: "",
          label: "",
          children: [
            {
              value: "",
              label: ""
            }
          ]
        }
      ]
    };
  },
  props: ["cityId", "areaId"],
  
  updated() {
    // console.log(this.cityId,this.areaId);
    
    this.value[0] = this.cityId;
    this.value[1] = this.areaId;
  },
  methods: {
    handleChange(value) {
      this.$emit("getaddress", value);
    },
    getList() {
      let cityurl = "/city/allCity";
      let areaurl = "/area/allArea";
      let cityPromise = this.$axios.get(cityurl);
      let areaPromise = this.$axios.get(areaurl);
      Promise.all([cityPromise, areaPromise])
        .then(res => {
          let cityList = res[0].cities;
          let areaList = res[1].areas;
          let newcitylist = cityList.map(city => {
            // 找出城市对应的地区列表
            let newAreaList = areaList.filter(area => {
              return area.cityId == city.cityId;
            });
            // 地区列表变成组件需要的数据结构
            newAreaList = newAreaList.map(area => {
              return {
                value: area.areaId,
                label: area.name
              };
            });
            return {
              value: city.cityId,
              label: city.name,
              children: newAreaList,
              disabled: newAreaList.length === 0
            };
          });
          let arr = [];
          for (let i = 0; i < newcitylist.length; i++) {
            if (newcitylist[i].disabled == false) {
              arr.push(newcitylist[i]);
            }
          }
          this.options = arr;
        })
        .catch(err => {
          this.$message.error(err);
        });
    }
  },

  created() {
    this.getList();
  }
};
</script>
